<?php

/**
 * 
 * Enter description here ...
 * @author crackerjack
 *
 */
class App_Db_User extends App_Db_Table
{	
	/**
	 * 
	 * Enter description here ...
	 * @var unknown_type
	 */
	protected $_name = 'users';
	 /**
	 * 
	 * Enter description here ...
	 * @var unknown_type
	 */
	protected $_primaryKey = 'id';
	
	/**
	 * 
	 * Enter description here ...
	 * @var unknown_type
	 */
	private $_username;
	
	/**
	 * 
	 * Enter description here ...
	 * @var unknown_type
	 */
	private $_password;
	
	/**
	 * 
	 * Enter description here ...
	 * @var unknown_type
	 */
	private $_lastLoginRecord;
	
	/**
	 * Enter description here...
	 *
	 */
	public function init()
	{
		
	}
	
	/**
	 * 
	 * Enter description here ...
	 */
	public function getAllUsers($limit = null)
	{
		$result = is_null($limit) ? $this->select() : $this->select()->limit($limit,0);
		return $this->fetchAll($result);
	}
	
	/**
	 * 
	 * Enter description here ...
	 * @param unknown_type $id
	 */
	public function getUserById($id)
	{
		$result = $this->select()->limit(1,0)->where("id = '{$id}'");
		return $this->fetchRow($result);
	}
	
	/**
	 * 
	 * Enter description here ...
	 * @param unknown_type $username
	 */
	public function setUsername($username)
	{
		$this->_username = strip_tags(mysql_escape_string($username));
	}
	
	/**
	 * 
	 * Enter description here ...
	 * @param unknown_type $password
	 */
	public function setPassword($password)
	{
		$this->_password = SHA1($password);
	}
	
	/**
	 * 
	 * Enter description here ...
	 */
	public function login()
	{
		if(isset($this->_username,$this->_password)){
			$result = $this->select()->setIntegrityCheck(false)
					->from(array('u' => 'users'))
					->joinInner(array('p' => 'positions'),'p.id = u.position', array('position_id' => 'id'))
					->where('username = ?',$this->_username)
					->where('password = ?',$this->_password)
					->limit(1,0);
			$result = $this->fetchRow($result);
			if(has_value($result)){
				$this->_lastLoginRecord['firstname'] 	= $result->firstname;
				$this->_lastLoginRecord['lastname'] 	= $result->lastname;
				$this->_lastLoginRecord['username'] 	= $result->username;
				$this->_lastLoginRecord['password'] 	= $result->password;
				$this->_lastLoginRecord['id'] 			= $result->id;
				$this->_lastLoginRecord['position']		= $result->position;
				$this->_lastLoginRecord['position_id']	= $result->position_id;
				return true;
			}
			return false;
		} else {
			throw new Exception('Set first username and password');
		}
	}
	
	/**
	 * 
	 * Enter description here ...
	 */
	//public function logoutById($id)
	//{
	//	if($this->update(array('logged_in'=>0), "id={$id}") == 1){
	//		return true;
	//	}
	//	return false;
	//}
	
	/**
	 * 
	 * Enter description here ...
	 */
	public function getLoginInfo()
	{
		return isset($this->_lastLoginRecord) ? $this->_lastLoginRecord : array();
	}
} 


?>